/*
 * Copyright 2009 Tran Nhut Trung.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */
package com.gdevelop.gwtxp.rebind;

import com.google.gwt.core.ext.TreeLogger;

import java.io.ByteArrayOutputStream;
import java.io.File;

import java.io.IOException;
import java.io.InputStream;

import java.net.URL;
import java.net.URLClassLoader;

import java.net.URLConnection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * Class loader used during development
 */
public class DevClassLoader extends URLClassLoader{
  private TreeLogger.Type logLevel = TreeLogger.DEBUG;
  private TreeLogger logger;
  private String[] reloadablePackages;
  private List<String> searchPath = new ArrayList<String>();
  
  private Map<String, Class> cachedClassByte = new HashMap<String, Class>();

  public DevClassLoader(ClassLoader parent, TreeLogger logger, String[] reloadablePackages) {
    super(new URL[0], parent);
    
    this.logger = logger.branch(logLevel, "DevClassLoader");
    this.reloadablePackages = reloadablePackages;

    String classPath = System.getProperty("java.class.path");
    StringTokenizer st = new StringTokenizer(classPath, File.pathSeparator);
    while (st.hasMoreTokens()){
      String path = st.nextToken();
      searchPath.add(path);
    }
  }

  public Class loadClass(String name) throws ClassNotFoundException {
    if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("com.google")){
      return super.loadClass(name);
    }
    Class cachedClass = cachedClassByte.get(name);
    if (cachedClass != null){
      return cachedClass;
    }

    boolean reloadable = false;
    for (String reloadablePackage : reloadablePackages){
      if (name.startsWith(reloadablePackage)){
        reloadable = true;
        break;
      }
    }
    if (!reloadable){
      return super.loadClass(name);
    }
    
    TreeLogger logger = this.logger.branch(logLevel, "Reloading class " + name);
    
    String fullName = "";
    String className = name.replace('.', '/') + ".class";
    for (String path : searchPath){
      if (path.endsWith("jar")){
        fullName = "jar:file:" + path + "!/" + className;
      }else{
        if (!path.endsWith(File.separator)){
          path = path + File.separator;
        }
        fullName = "file:" + path + className;
      }
      logger.log(logLevel, "Try to load class from " + path);

      try{
        URL url = new URL(fullName);
        URLConnection connection = url.openConnection();
        InputStream input = connection.getInputStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int len;
        byte[] b = new byte[1024];
        
        while ((len = input.read(b)) > 0){
          buffer.write(b, 0, len);
        }
        input.close();
        
        byte[] classData = buffer.toByteArray();
        Class clazz = defineClass(name, classData, 0, classData.length);
        cachedClassByte.put(name, clazz);
        return clazz;
      }catch(IOException e){
        // e.printStackTrace();
        logger.log(logLevel, "Could not load class " + name + " from " + path);
        continue;
      }
    }
    
    logger.log(logLevel, "Load class " + name + " using parent class loader");
    return super.loadClass(name);
  }
}
